package morning.cat.exception.notruntimeexception;

import org.junit.Test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * https://my.oschina.net/mengzhang6/blog/2993479
 *
 * @author mengzhang6
 * @date 2018/12/25 9:49
 */
public class IOExceptionTest {

    /**
     * 利用Try-Catch-Finally管理资源（旧的代码风格）
     * 在java7以前，程序中使用的资源需要被明确地关闭，这个体验有点繁琐。
     *
     * @throws IOException
     */
    @Test
    public void test1() throws IOException {
        String filepath = "D:\\gui-config.json";
        BufferedReader br = null;
        String curline;

        try {
            br = new BufferedReader(new FileReader(filepath));
            while ((curline = br.readLine()) != null) {
                System.out.println(curline);

            }
        } catch (FileNotFoundException e) {
            throw new FileNotFoundException("文件xxx不存在，请检查后重试。");
            // trturn xxx;
        } catch (IOException e) {
            throw new IOException("文件xxx读取异常。");
        } finally {

            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                throw new IOException("关闭流异常。");
            }
        }
    }

    /**
     * try-with-resource 结构(jdk7 新特性)
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        String filepath = "D:\\gui-config.json";

        //
        try (
                FileReader fileReader = new FileReader(filepath);
                BufferedReader br = new BufferedReader(fileReader)
        ) {
            String curline = null;
            while ((curline = br.readLine()) != null) {
                System.out.println(curline);
            }
        }

    }

    @Test
    public void test3() throws Exception {
        try (AutoCloseTestModel autoCloseTestModel = new AutoCloseTestModel()) {
            autoCloseTestModel.run(false);
        }
    }

}
